
/**
 * Load lab service of selected group
 * @param ticketId
 * @param labGroupId
 * @return
 */
function loadLabServicesOfSelectedGroup(ticketId, labGroupId) {
	$.ajax({
		type:		"GET",
		url:		"../LabAssignment/ListLabServicesOfSelectedGroupAjax?set_ajax_view",
		data:		"labGroupId=" + labGroupId + "&ticketId=" + ticketId,		
		dataType:   "json",		
		success: 	function(data) {
			var optionts = buildLabServicesSelectOption(data.result, labGroupId, "labAssignmentAssignedServices");
			$("select#labAssignmentServiceDetail").html(optionts);
			$("select#labAssignmentServiceDetail").attr('groupid',labGroupId);
			
		}
	});		

}
/**
 * Add selected lab service into assigned list.
 * @return
 */
function selectLabServices() {
	var selectedGroup = $('select#labAssignmentGroup :selected');
	var selectingServices = $('select#labAssignmentServiceDetail :selected');
	var selectedServices = $('select#labAssignmentAssignedServices :option');
	
	selectingServices.each(function() {		
		addItemIntoSelectedServices(selectedGroup, $(this));		
	});	
	
	calculateTotalPrices();
	
}
 /**
  * Calculate price of assigned services.
  * @param ticketId
  * @param labGroupId
  * @return
  */
function calculateTotalPrices() {
	var text = '';
	var selectedServices = $('select#labAssignmentAssignedServices :option');
	var price = 0;
	var insPrice = 0;
	var patientPrice = 0;
	
	selectedServices.each(function() {
		if ($(this).attr('groupid') != 0) {
			price += parseInt($(this).attr('price'));
			insPrice += parseInt($(this).attr('insurance_price'));
			patientPrice += parseInt($(this).attr('patient_price'));
		}
		
	});
	var lcInt = locale(decimalPoint, thousandSep, 0);
	
	$('span#labAssignmentTotalPrice').html(_("Assigned services [Price:{0}]", toLcString(patientPrice, lcInt)));
}
/**
 * Add selected services into assigned list.
 * @param groupObj
 * @param ItemObject
 * @return
 */
function addItemIntoSelectedServices(groupObj,ItemObject) {	
	var group = getGroup(groupObj);	
	var item = getItem(ItemObject.val());
	if (group != null ) {
		if (item == null) {
			group.append(ItemObject);
		}
	} 
}

/**
 * unselected assigned services
 * @return
 */
function unSelectServicesFromList() {
	var selectedServices = $('select#labAssignmentAssignedServices :selected');
	var labAssignmentSelectedGroupId = $('select#labAssignmentServiceDetail').attr('groupid');
	var labAssignmentDetail = $('select#labAssignmentServiceDetail');
	selectedServices.each(function() {		
		if (labAssignmentSelectedGroupId != null 
				&& labAssignmentSelectedGroupId == $(this).attr('groupid')) {
			var option = "<option groupid='" + $(this).attr('groupid') + "' " 
			+ " value='" + $(this).val() + "' "  
			+ " price='" + $(this).attr('price') + "' " 
			+ " insurance_price='" + $(this).attr('insurance_price') + "' " 
			+ " patient_price='" + $(this).attr('patient_price') + "' " 
			+ ">" + $(this).html() + "</option>";
			labAssignmentDetail.append(option);						
		}
		$(this).remove();
	});
	
	calculateTotalPrices();
	removeEmptyAssignedServiceGroup();
	
}

/**
 * Get group in assigned list.
 * @param groupObj
 * @return
 */
function getGroup(groupObj) {
	var selectedServicesGroup = $('#labAssignmentAssignedServices :option');
	var group = null;
	selectedServicesGroup.each(function() {	
		
		if ($(this).attr('groupid') == 0 
				&& $(this).attr('value') == groupObj.val()) {
			group = $(this);
		}		
		
	});
	if (group == null) {
		$('#labAssignmentAssignedServices').append("<optgroup groupid = '0' value='" +
				groupObj.val() + "' label='" + groupObj.html() + "'></optgroup>");	
		return getGroup(groupObj);
	}
	return group;
}
 /**
  * remove all the empty group in assigned service list.
  * 
  */
function removeEmptyAssignedServiceGroup() {
	$('#labAssignmentAssignedServices :option').each(function() {
		
		if ($(this).attr('groupid') == 0 && countItemInGroup('labAssignmentAssignedServices', $(this).attr('value')) == 0 ) {			
			$(this).remove();			
		}		
	});	
}

function countItemInGroup(listId, groupId) {
	var count = 0;
	$('#' + listId + ' :option').each(function() {		
		if ($(this).attr('groupid') != 0 && $(this).attr('groupid') == groupId) {
			count++;			
		}	
	});
	return count;
}
/**
 * get item of assigned list. 
 * @param groupId
 * @param itemId
 * @return
 */
function getItem(groupId, itemId) {
	var selectedServicesGroup = $('#labAssignmentAssignedServices :option');
	selectedServicesGroup.each(function() {
		if ($(this).attr('groupid') == groupId 
				&& $(this).attr('value') == itemId) {
			return $(this);
		}		
	});
	return null;
}
/**
 * Build option for selected group.
 * @param arrLabServices
 * @param labGroupId
 * @param listIdToexcluse
 * @return
 */
function buildLabServicesSelectOption(arrLabServices, labGroupId, listIdToexcluse) {
	var option = "";
	var arr=[];
	$("#" + listIdToexcluse + " option").each(function() {
		arr[$(this).val()] = 'yes';
	});
	var lcInt = locale(decimalPoint, thousandSep, 0);			
	

	for(var index in arrLabServices){
		
		if (arr[arrLabServices[index].service_id] == null) {
			var text = _("{0} [Price:{1}]",arrLabServices[index].name, toLcString(arrLabServices[index].patient_price, lcInt));
			option += "<option groupid='" + labGroupId + "' " 
			+ " value='" + arrLabServices[index].service_id + "' "  
			+ " price='" + arrLabServices[index].price + "' " 
			+ " insurance_price='" + arrLabServices[index].insurance_price + "' " 
			+ " patient_price='" + arrLabServices[index].patient_price + "' " 
			+ ">" + text + "</option>";
		}

	}
	return option;
}
/**
 * Validate lab Assignment form.  
 * @return
 * false if not valid
 * true if valid
 */
function validateBeforeSave() {
	if (!validateSelectBox('labAssignmentDoctorName',_('Please select doctor'),
			'labAssignmentStatusMessage')) {
		return false;
	}

	if (!checkMonth($('#labAssignment_mm'),true,'','#labAssignmentStatusMessage')) {
		$('#labAssignmentStatusMessage').show();
		return false;
	} 

	if (!checkDay($('#labAssignment_dd'),true,'','#labAssignmentStatusMessage' )) {
		$('#labAssignmentStatusMessage').show();	
		return false;
	}	
	if (!checkHour($('#labAssignmentTime'), true, '', 'labAssignmentStatusMessage')) {
		$('#labAssignmentStatusMessage' ).show();	
		return false;
	}

	var res 	= 	checkDate($('#labAssignment_yyyy'),
			$('#labAssignment_mm'),
			$('#labAssignment_dd'), true, '', '#labAssignmentStatusMessage', false);	

	if(!res){	
		$('#labAssignmentStatusMessage').show();
		return false;
	}
	if (countItemInListBox('labAssignmentAssignedServices') == 0) {
		$('#labAssignmentStatusMessage').text(_('Please select laboratory service')).show();
        $('#labAssignmentStatusMessage').css("font-style", "italic");
        $('#labAssignmentStatusMessage').css("color","red");
        return false;
    }
	
	$('#labAssignmentStatusMessage').html('');
	return true;

}
/**
 * Get assigned services id
 * @param assignedServiceListId
 * @return list of assignedService id.
 */
function prepareAssignedServicesForSave(assignedServiceListId) {

	var paras = '';
	$("#" + assignedServiceListId + " option").each(function() {
		paras += '&labAssignedItem[]=' + $(this).val();
		paras += '&labGroup[]=' + $(this).attr('groupid');
	});
	return paras;
}
/**
 * Create assignment.
 * @param ticketId
 * @param dialog
 * @param print
 * @return
 */
function createLabAssignment(ticketId, idOfActionAfterCreating, dialog, print) {
	if (validateBeforeSave() == false ) {
		return;
	}
	var dt=new Date();
	var second = (dt.getSeconds() < 10 ? '0' + dt.getSeconds(): dt.getSeconds());

	var requestedTime = $('#labAssignment_yyyy').val() 
	+ '-' 
	+ $('#labAssignment_mm').val()
	+ '-'
	+ $('#labAssignment_dd').val()
	+ ' '
	+ $('#labAssignmentTime').val()
	+ ':'
	+ second;

	var paras = 'ticketId=' + ticketId; 
	paras += prepareAssignedServicesForSave("labAssignmentAssignedServices");	
	paras += "&doctorId=" + $('#labAssignmentDoctorName :selected').val();
	paras += "&requestedTime=" + requestedTime;
	paras += "&diagnosis=" + $("#labAssignmentDiagnosis").val();
	$.ajax({
		type:		"GET",
		url:		"../LabAssignment/CreatedAssignmentAjax?set_ajax_view",
		data:		paras,		
		dataType:   "json",
		success: 	function(data) {

		if (data.error.code ==  'OK') {
			dialog.dialog('close');	
			if (idOfActionAfterCreating != null 
					&& $.trim(idOfActionAfterCreating) != '') {
				$('#' + idOfActionAfterCreating).trigger('click');				
			}
			if (print == true) {
				printLabAssignment(data.result);
			}
		} else {
			displayError(data.error.mess);				
		}

	}
	});	
}
 function printLabAssignment(labAssignmentTicketId) {
		
		var url='../LabAssignment/PrintAssignment?set_print_view&labAssignmentTicketId=' 
			+ labAssignmentTicketId ;
		window.open(url, '', 'scrollbars=yes, menubar=no, width=800, height=600, resizable=yes, toolbar=no, location=no, status=no');

}